package com.bi.onlineEducation.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @ClassName FtpUtil
 * @Author Administrator
 * @Date 2021/2/14 19:31
 * @Version 1.0
 */
@Component
public class FtpUtil {

    private final static Log logger = LogFactory.getLog(FtpUtil.class);

    private final static String ftpPath = "upgrade/video/";

    @Value("${drive.ftpHost}")
    public String ftpHost;
    @Value("${drive.ftpPort}")
    public Integer ftpPort;
    @Value("${drive.ftpUserName}")
    public String ftpUserName;
    @Value("${drive.ftpPassword}")
    public String ftpPassword;
    @Value("${upload.servicePath}")
    public String servicePath;

    /**
     * 获取FTPClient对象
     *
     * @param ftpHost     FTP主机服务器
     * @param ftpPassword FTP 登录密码
     * @param ftpUserName FTP登录用户名
     * @param ftpPort     FTP端口 默认为21
     * @return
     */
    public static FTPClient getFTPClient(String ftpHost, String ftpUserName, String ftpPassword, int ftpPort) {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient = new FTPClient();
            ftpClient.connect(ftpHost, ftpPort);              // 连接FTP服务器
            ftpClient.login(ftpUserName, ftpPassword);        // 登陆FTP服务器
            ftpClient.setControlEncoding("UTF-8");             // 中文支持
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setSendBufferSize(100000000);
            ftpClient.setBufferSize(100000000);
            ftpClient.setReceieveDataSocketBufferSize(100000000);
            ftpClient.setSendDataSocketBufferSize(100000000);
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                logger.info("未连接到FTP，用户名或密码错误。");
                ftpClient.disconnect();
            } else {
                logger.info("FTP连接成功。");
            }
        } catch (SocketException e) {
            e.printStackTrace();
            logger.info("FTP的IP地址可能错误，请正确配置。");
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("FTP的端口错误,请正确配置。");
        }
        return ftpClient;
    }


    /**
     * @param fileName 原文件名称
     * @param input    输入流
     * @return
     */
    public String uploadFile(String fileName, InputStream input) {
        String result = null;
        FTPClient ftpClient = new FTPClient();
        try {
            int reply;
            // 获取FTP连接
            ftpClient = getFTPClient(
                    ftpHost,
                    ftpUserName,
                    ftpPassword,
                    ftpPort);

            ftpClient.changeWorkingDirectory(ftpPath);

            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return null;
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

            fileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();


            fileName = new String(fileName.getBytes("GBK"), FTP.DEFAULT_CONTROL_ENCODING);    //编码文件名，支持中文文件名
            //上传文件
            if (!ftpClient.storeFile(fileName, input)) {
                return null;
            }
            input.close();
            ftpClient.logout();
            result = servicePath + fileName;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return result;
    }

    /**
     * 根据文件名删除ftp文件
     *
     * @param fileName 文件名
     * @return
     */
    public Boolean deleteFile(String fileName) {
        String result = null;
        FTPClient ftpClient = new FTPClient();
        try {
            int reply;
            // 获取FTP连接
            ftpClient = getFTPClient(
                    ftpHost,
                    ftpUserName,
                    ftpPassword,
                    ftpPort);

            ftpClient.changeWorkingDirectory(ftpPath);

            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                return false;
            }
            return ftpClient.deleteFile(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return false;
    }

}

